package com.i2works.smartluolong.api.controller.fooddrug;

import com.i2works.smartluolong.api.controller.common.CommonItemController;
import com.i2works.smartluolong.utils.base.*;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.entity.flow.FlowInfoDO;
import com.i2works.smartluolong.web.entity.fooddrug.*;
import com.i2works.smartluolong.web.service.flow.IFlowInfoService;
import com.i2works.smartluolong.web.service.flow.IFlowProcessService;
import com.i2works.smartluolong.web.service.flow.IFlowService;
import com.i2works.smartluolong.web.service.flow.IFlowTemplateService;
import com.i2works.smartluolong.web.service.fooddrug.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 食药申请控制器
 *
 * @author Liu YaPeng
 * @date 2017/9/27 20:07
 */

@Controller
@RequestMapping("/fooddrugApply")
public class FooddrugApplyController extends CommonItemController {
	
 
    private final IFooddrugApplyService fooddrugApplyService;
    
    private final IFooddrugApplyImagesService fooddrugApplyImagesService;
    
    private final IFooddrugApplyMemberService fooddrugApplyMemberService;
    
    private final IFooddrugApplyDeviceService fooddrugApplyDeviceService;
    
    private final IFooddrugApplyLicenseService fooddrugApplyLicenseService;
    
    private final IFlowInfoService flowInfoService;
    

    
	@Autowired
    public FooddrugApplyController(IFlowInfoService flowInfoService,IFlowTemplateService flowTemplateService, IFlowService flowService, IFlowProcessService flowProcessService,IFooddrugApplyService fooddrugApplyService,IFooddrugApplyImagesService fooddrugApplyImagesService,IFooddrugApplyMemberService fooddrugApplyMemberService,IFooddrugApplyDeviceService fooddrugApplyDeviceService,IFooddrugApplyLicenseService fooddrugApplyLicenseService) {
	   super(flowTemplateService, flowService, flowProcessService);
	   this.fooddrugApplyService=fooddrugApplyService;
       this.fooddrugApplyImagesService=fooddrugApplyImagesService;
       this.fooddrugApplyMemberService=fooddrugApplyMemberService;
       this.fooddrugApplyDeviceService=fooddrugApplyDeviceService;
       this.fooddrugApplyLicenseService=fooddrugApplyLicenseService;
       this.flowInfoService=flowInfoService;
    }

    @PostMapping("/base")
    @ResponseBody
    public Result base(Integer id) {
    	Map<String, Object> map=new HashMap<String, Object>();
    	try {
    		FooddrugApplyQuery query=new FooddrugApplyQuery();
    		query.setId(id);
			FooddrugApplyDO fooddrugApplyDO =fooddrugApplyService.query(query);
			map.put("id", fooddrugApplyDO.getId());
			map.put("companyName", fooddrugApplyDO.getCompanyName());
			map.put("companyLicenseList", queryAttach(id,1));
			map.put("rentalContractList", queryAttach(id,2));
			map.put("layoutList", queryAttach(id,3));
			map.put("operatingProceduresList", queryAttach(id,4));
			map.put("orientationMapList", queryAttach(id,5));
		} catch (ServiceException e) {
			e.printStackTrace();
			R.error();
		}
        return R.success(map);
    }
    
    
  /**
   * @param  FooddrugApplyDO fooddrugApplyDO
   * */
    @PostMapping("/saveBase")
    @ResponseBody
    public Result saveBase(FooddrugApplyDO fooddrugApplyDO) {
    	Map<String, Object> map=new HashMap<String,Object>();
    	try {
    		if(fooddrugApplyDO.getId()==null) {
        		fooddrugApplyDO.setCreateName(getUserName());
        		fooddrugApplyDO.setUpdateName(getUserName());
        		fooddrugApplyDO.setApplyStatus(0);
        		fooddrugApplyService.save(fooddrugApplyDO);
        		FlowInfoDO flowInfoDO=new FlowInfoDO();
    			flowInfoDO.setUserId(fooddrugApplyDO.getUserId());
    			flowInfoDO.setItemId(fooddrugApplyDO.getId());
    			flowInfoDO.setItemName(fooddrugApplyDO.getCompanyName()+FooddrugConstant.APPLY_TITLE);
    			flowInfoDO.setItemStatus(0);
    			flowInfoDO.setComplete(0);
    			flowInfoDO.setItemType(FooddrugConstant.APPLY_ITEM_TYPE);
    			flowInfoDO.setCreateName(getUserName());
    			flowInfoDO.setUpdateName(getUserName());
    			flowInfoService.save(flowInfoDO);
    		}else {
        		fooddrugApplyDO.setUpdateName(getUserName());
    			fooddrugApplyService.update(fooddrugApplyDO);
    			fooddrugApplyImagesService.deleteApply(fooddrugApplyDO.getId());
    		}
  			saveAttach(fooddrugApplyDO.getCompanyLicenseList(),true,fooddrugApplyDO.getId(),1);
    		saveAttach(fooddrugApplyDO.getRentalContractList(),true,fooddrugApplyDO.getId(),2);
    		saveAttach(fooddrugApplyDO.getLayoutList(),true,fooddrugApplyDO.getId(),3);
    		saveAttach(fooddrugApplyDO.getOperatingProceduresList(),true,fooddrugApplyDO.getId(),4);
    		saveAttach(fooddrugApplyDO.getOrientationMapList(),true,fooddrugApplyDO.getId(),5);
    		map.put("applyId", fooddrugApplyDO.getId());
		} catch (ServiceException e) {
			e.printStackTrace();
			R.error();
		}
        return R.success(map);
    }
    
    @PostMapping("/agent")
    @ResponseBody
    public Result applyAgent(Integer applyId) {
    	Map<String,Object> map=new HashMap<String,Object>();
		try {
			FooddrugApplyMemberQuery query=new FooddrugApplyMemberQuery();
			query.setApplyId(applyId);
			query.setRole(1);
			List<FooddrugApplyMemberDO> list=fooddrugApplyMemberService.queryList(query);
			FooddrugApplyMemberDO agent=new FooddrugApplyMemberDO();
			if(list.size()!=0) {
				agent= list.get(0);
				queryMember(agent,map);
			}else {
				agent.setApplyId(applyId);
				queryMember(agent,map);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			return R.error();
		}
        return R.success(map);
    }
    

    @PostMapping("/saveAgent")
    @ResponseBody
    public Result saveAgent(FooddrugApplyMemberDO agent) {
    	Map<String, Object> map=new HashMap<String,Object>();
    	try {
    		agent.setRole(1);
    		if(agent.getId()==null) {
    			agent.setCreateName(getUserName());
    			agent.setUpdateName(getUserName());
    			fooddrugApplyMemberService.save(agent);	
    		}else {
    			agent.setUpdateName(getUserName());
    			fooddrugApplyMemberService.update(agent);	
    		}
    		map.put("applyId", agent.getApplyId());
		} catch (ServiceException e) {
			e.printStackTrace();
	        return R.error();
		}
        return R.success(map);
    }

    @PostMapping("/legal")
    @ResponseBody
    public Result applyLegal(Integer applyId) {
    	Map<String, Object> map=new HashMap<String, Object>();
		try {
			FooddrugApplyMemberQuery query=new FooddrugApplyMemberQuery();
			query.setApplyId(applyId);
			query.setRole(2);
			List<FooddrugApplyMemberDO> list=fooddrugApplyMemberService.queryList(query);
			FooddrugApplyMemberDO legal=new FooddrugApplyMemberDO();
			if(list.size()!=0) {
				legal= list.get(0);
				queryMember(legal,map);
			}else {
				legal.setApplyId(applyId);
				queryMember(legal,map);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		map.put("nationMap",NationUtil.getNationMap());//民族常量
        return R.success(map);
    }


	@PostMapping("/saveLegal")
	@ResponseBody
    public Result saveLegal(FooddrugApplyMemberDO legal) {
		try {
			legal.setRole(2);
			if(legal.getId()==null) {
				legal.setCreateName(getUserName());
				legal.setUpdateName(getUserName());
				fooddrugApplyMemberService.save(legal);
			}else {
				legal.setUpdateName(getUserName());
				fooddrugApplyMemberService.update(legal);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			return R.error();
		}
		return R.success();
    }
	
    @PostMapping("/license")
    @ResponseBody
    public Result applyLicense(Integer applyId) {
    	Map<String, Object> map=new HashMap<String, Object>();
    	try {
    		FooddrugApplyLicenseQuery query =new FooddrugApplyLicenseQuery();
    		query.setApplyId(applyId);
			List<FooddrugApplyLicenseDO> list=fooddrugApplyLicenseService.queryList(query);
			FooddrugApplyLicenseDO	 license=new FooddrugApplyLicenseDO();
			if(list.size()!=0) {
				license=list.get(0);
			}
			map.put("id",license.getId());
			map.put("premises",license.getPremises());
			map.put("businessArea",license.getBusinessArea());
			map.put("businessNature",license.getBusinessNature());
			map.put("subjectFormats",license.getSubjectFormats());
			map.put("businessCategory",license.getBusinessCategory());
			map.put("networkSales",license.getNetworkSales());
			map.put("storeSales",license.getStoreSales());
			map.put("schoolCanteen",license.getSchoolCanteen());
			map.put("businessProject",license.getBusinessProject()==null?"":license.getBusinessProject());
			map.put("cookedFood",license.getCookedFood());
			map.put("bomemadeWine",license.getBomemadeWine());
			map.put("decoratingCake",license.getDecoratingCake());
			map.put("freshMilk",license.getFreshMilk());
		} catch (ServiceException e) {
			e.printStackTrace();
			return R.error();
		}
        return R.success(map);
    }
    
    @PostMapping("/saveLicense")
    @ResponseBody
    public Result saveLicense(FooddrugApplyLicenseDO license) {
    	Map<String, Object> map=new HashMap<String, Object>();
		try {
			if(license.getId()==null) {
				license.setCreateName(getUserName());
				license.setUpdateName(getUserName());
				fooddrugApplyLicenseService.save(license);
			}else {
				license.setUpdateName(getUserName());
				fooddrugApplyLicenseService.update(license);
			}
			map.put("applyId",license.getApplyId());
		} catch (ServiceException e) {
			e.printStackTrace();
			return R.error();
		}
        return R.success(map);
    }
    

    @PostMapping("/member/api")
    @ResponseBody
    public Result queryMemberApi(Integer applyId,Integer role,Integer job) {
        try {
            //当前用户
        	FooddrugApplyMemberQuery query=new FooddrugApplyMemberQuery();
                   	query.setApplyId(applyId);
                  	query.setRole(role);
                   	query.setJob(job);
            Integer queryCount = fooddrugApplyMemberService.queryCount(query);
            List<FooddrugApplyMemberDO> queryList=new ArrayList<FooddrugApplyMemberDO>();
            if (queryCount > 0) {
            	queryList= fooddrugApplyMemberService.queryList(query);
            }
            return R.success(queryList, queryCount);
        } catch (ServiceException e) {
            return R.error();
        }
    }


    
    /**
     * 删除
     */
    @PostMapping("/deleteMember")
    @ResponseBody
    public Result deleteMember(Integer id) {
        try {
        	fooddrugApplyMemberService.delete(id);
        } catch (Exception e) {
            R.error();
        }
        return R.success();
    }


    @PostMapping("/saveEmployee")
    @ResponseBody
    public Result saveEmployee(FooddrugApplyMemberDO employee) {
    	Map<String, Object> map=new HashMap<String, Object>();
    	try {
    		employee.setRole(3);
    		if(employee.getId()==null) {
    			employee.setCreateName(getUserName());
        		employee.setUpdateName(getUserName());
        		fooddrugApplyMemberService.save(employee);	
    		}else {
    			employee.setUpdateName(getUserName());
        		fooddrugApplyMemberService.update(employee);	
    		}
    		map.put("applyId",employee.getApplyId());
    		map.put("id", employee.getId());
		} catch (ServiceException e) {
			e.printStackTrace();
			return R.error();
		}
        return  R.success(map);
    }
    
    
    
    @PostMapping("/saveTechnician")
    @ResponseBody
    public Result saveTechnician(FooddrugApplyMemberDO technician) {
    	Map<String, Object> map=new HashMap<String, Object>();
		try {
			technician.setRole(4);
			if(technician.getId()==null) {
				technician.setCreateName(getUserName());
				technician.setUpdateName(getUserName());
				technician.setJob(1);
				fooddrugApplyMemberService.save(technician);
			}else {
				technician.setUpdateName(getUserName());
				fooddrugApplyMemberService.update(technician);
			}
		 	map.put("applyId",technician.getApplyId());
		 	map.put("id",technician.getId());
		} catch (ServiceException e) {
			e.printStackTrace();
			return R.error();
		}
        return R.success(map);
    }


    
    @PostMapping("/saveManager")
    @ResponseBody
    public Result saveManager(FooddrugApplyMemberDO manager) {
    	Map<String, Object> map=new HashMap<String, Object>();
		try {
			manager.setRole(4);
			if(manager.getId()==null) {
				manager.setCreateName(getUserName());
				manager.setUpdateName(getUserName());
				manager.setJob(2);
				fooddrugApplyMemberService.save(manager);
			}else {
				manager.setUpdateName(getUserName());
				fooddrugApplyMemberService.update(manager);
			}
   		 map.put("applyId",manager.getApplyId());
   		 map.put("id", manager.getId());
		} catch (ServiceException e) {
			e.printStackTrace();
			return R.error();
		}
        return  R.success(map);
    }
    

    @PostMapping("/query/member") 
    @ResponseBody
    public Result queryManager(Integer id) {
    	Map<String, Object> map =new HashMap<String, Object>();
        if(id!=null) {
        	try {
        	map.put("nationMap",NationUtil.getNationMap());//民族常量
        	FooddrugApplyMemberQuery query=new FooddrugApplyMemberQuery();
        	query.setId(id);
        	FooddrugApplyMemberDO member=fooddrugApplyMemberService.query(query);
        	queryMember(member,map);    
			} catch (ServiceException e) {
				e.printStackTrace();
				return R.error();
			}
        }
        return R.success(map);
    }

  

    
    @PostMapping("/query/device")
    @ResponseBody
    public Result queryDevice(Integer id) {
    	Map<String, Object> map=new HashMap<String, Object>();
        if(id!=null) {
        	try {
        	FooddrugApplyDeviceQuery query=new FooddrugApplyDeviceQuery();
        	query.setId(id);
        	FooddrugApplyDeviceDO device=fooddrugApplyDeviceService.query(query);
        	map.put("applyId", device.getApplyId());
        	map.put("deviceName", device.getDeviceName());
        	map.put("number", device.getNumber());
        	map.put("site", device.getSite());
			} catch (ServiceException e) {
				e.printStackTrace();
				return R.error();
			}
        }
    	return R.success(map);
    }
    

    @PostMapping("/saveDevice")
    @ResponseBody
    public Result saveDevice(FooddrugApplyDeviceDO device) {
    	Map<String, Object> map=new HashMap<String,Object>();
    	try {
    		if(device.getId()==null) {
    			device.setCreateName(getUserName());
    			device.setUpdateName(getUserName());
    			fooddrugApplyDeviceService.save(device);
    		}else {
    			device.setUpdateName(getUserName());
    			fooddrugApplyDeviceService.update(device);
    		}
			map.put("applyId",device.getApplyId());
			map.put("id",device.getId());
		} catch (ServiceException e) {
			e.printStackTrace();
			return R.error();
		}
        return R.success(map);
    } 

    
    /**
     * 删除
     */
    @PostMapping("/deleteDevice")
    @ResponseBody
    public Result deleteDevice( Integer id) {
        try {
        	fooddrugApplyDeviceService.delete(id);
        } catch (Exception e) {
           return R.error();
        }
        return R.success();
    }

    
    /**
     * 查询项目列表接口
     */
    @RequestMapping("/device/api")
    @ResponseBody
    public Result queryDeviceApi(Integer applyId) {
        try {
            //当前用户
        	FooddrugApplyDeviceQuery query=new FooddrugApplyDeviceQuery();
                    	query.setApplyId(applyId);
            Integer queryCount = fooddrugApplyDeviceService.queryCount(query);
            List<FooddrugApplyDeviceDO> queryList=new ArrayList<FooddrugApplyDeviceDO>();
            if (queryCount > 0) {
                queryList = fooddrugApplyDeviceService.queryList(query);
            }
            return R.success(queryList, queryCount);
        } catch (ServiceException e) {
            return R.error();
        }
    }
    

    /*
     * 食药申请提交
     * */
    @PostMapping("/saveApply")
    @ResponseBody
    public Result saveApply(FooddrugApplyDO fooddrugApplyDO) {
    	try {
			fooddrugApplyService.update(fooddrugApplyDO);
			FooddrugApplyQuery query=new FooddrugApplyQuery();
			query.setId(fooddrugApplyDO.getId());
			fooddrugApplyDO=fooddrugApplyService.query(query);
			FlowInfoDO flowInfoDO=new FlowInfoDO();
			flowInfoDO.setItemId(fooddrugApplyDO.getId());
			flowInfoDO.setItemType(FooddrugConstant.APPLY_ITEM_TYPE);
			flowInfoDO.setItemName(fooddrugApplyDO.getCompanyName()+FooddrugConstant.APPLY_TITLE);
			flowInfoDO.setItemStatus(1);
			flowInfoDO.setUserId(getUserId());
			flowInfoDO.setUpdateName(getUserName());
			flowInfoService.save(flowInfoDO);
			return R.success();
		} catch (ServiceException e) {
			e.printStackTrace();
			return R.error();
		}
    }
    
    
    @PostMapping("/view")
    @ResponseBody
    public Result view(Integer id) {
    	Map<String, Object> map=new HashMap<String, Object>();
    	try {
    		FooddrugApplyQuery query=new FooddrugApplyQuery();
    		query.setId(id);
    		FooddrugApplyDO fooddrugApplyDO =fooddrugApplyService.query(query);
    		map.put("id", fooddrugApplyDO.getId());
    		map.put("companyName", fooddrugApplyDO.getCompanyName());
    		map.put("companyLicenseList", queryAttach(id,1));
    		map.put("rentalContractList", queryAttach(id,2));
    		map.put("layoutList", queryAttach(id,3));
    		map.put("operatingProceduresList", queryAttach(id,4));
    		map.put("orientationMapList", queryAttach(id,5));
     		FooddrugApplyMemberQuery memberQuery=new FooddrugApplyMemberQuery();
    		memberQuery.setApplyId(id);
    		memberQuery.setRole(1);
    		List<FooddrugApplyMemberDO> agentList= fooddrugApplyMemberService.queryList(memberQuery);
    		map.put("agentList",agentList);
    		memberQuery.setRole(2);
    		List<FooddrugApplyMemberDO> legalList= fooddrugApplyMemberService.queryList(memberQuery);
    		map.put("legalList",legalList);
    		memberQuery.setRole(3);
    		List<FooddrugApplyMemberDO> employeeList= fooddrugApplyMemberService.queryList(memberQuery);
    		map.put("employeeList",employeeList);
    		FooddrugApplyDeviceQuery deviceQuery=new FooddrugApplyDeviceQuery();
    		deviceQuery.setApplyId(id);
    		List<FooddrugApplyDeviceDO> deviceList= fooddrugApplyDeviceService.queryList(deviceQuery);
    		map.put("deviceList",deviceList);
    		FooddrugApplyLicenseQuery licenseQuery=new FooddrugApplyLicenseQuery();
    		licenseQuery.setApplyId(id);
    		List<FooddrugApplyLicenseDO> licenseList= fooddrugApplyLicenseService.queryList(licenseQuery);
    		FooddrugApplyLicenseDO license=new FooddrugApplyLicenseDO();
    		if(licenseList.size()!=0) {
    			license=licenseList.get(0);
    			map.put("businessProjectMap",BusinessProjectUtil.getProjectMap(license.getBusinessProject()));
    		}
    		map.put("license",license);
    		map.put("businessCategoryList",BusinessCategoryEnum.values());
    		map.put("uploaderFilesDomain", AppConstant.UPLOAD_FILES_DOMAIN);
        	map.put("flowProcessList", queryFlowProcess(id,FlowItemTypeEnum.COMPANY_APPLY.getKey()));
    	} catch (ServiceException e) {
    		e.printStackTrace();
    		return R.error();
    	}
    	return R.success(map);
    }

    /**
     * 申请作废
     * */
    @PostMapping("/invalid/action")
    @ResponseBody
    public Result invalid(FlowInfoDO flowInfoDO) {
    	try {
    		flowInfoDO.setItemStatus(11);
    		flowInfoService.update(flowInfoDO);
    		FooddrugApplyDO applyDO=new FooddrugApplyDO();
    		applyDO.setId(flowInfoDO.getItemId());
    		applyDO.setApplyStatus(11);
    		fooddrugApplyService.update(applyDO);
    	} catch (ServiceException e) {
    		e.printStackTrace();
    		return R.error();
    	}
    	return R.success();
    }

    
    public Map<String,Object> queryMember(FooddrugApplyMemberDO member,Map<String,Object> map) {
          	if(member.getId()!=null) {
          		map.put("id", member.getId());
    	    }
          	map.put("applyId", member.getApplyId());
          	map.put("name", member.getName());
          	map.put("sex", member.getSex());
          	map.put("nation", member.getNation());
          	map.put("role", member.getRole());
          	map.put("job", member.getJob());
          	map.put("cardType", member.getCardType());
          	map.put("cardNumber", member.getCardNumber());
          	map.put("cardFrontPicture", member.getCardFrontPicture());
          	map.put("cardBackPicture", member.getCardBackPicture());
          	map.put("phone", member.getPhone());
          	map.put("tel", member.getTel());
          	map.put("email", member.getEmail());
          	map.put("householdAddress", member.getHouseholdAddress());
          	map.put("healthCertLeader", member.getHealthCertLeader());
          	map.put("healthCertNumber", member.getHealthCertNumber());
          	map.put("healthCertPicture", member.getHealthCertPicture());
    	    return map;
    }

   
    /**
     * 处理附件
     *
     * @param projectDO 项目
     * @param isUpdate  是否更新项目（更新就先删除以前图片，再新增）
     */
    private void saveAttach(List<String> attachList,Boolean isUpdate,Integer applyId,Integer type) throws ServiceException {
        if (CollectionUtils.isNotEmpty(attachList)) {
            if (isUpdate) {
                //删除附件(通过项目ID删除)
            	fooddrugApplyImagesService.delete(applyId);
            }
            //添加附件
            for (String attach : attachList) {
                    //判断url是否存在
                    String url = StringUtils.isNotBlank(attach) ? attach : GlobalConstant.NOPIC;
                    //写入文件
                    FooddrugApplyImagesDO fooddrugApplyImagesDO = new FooddrugApplyImagesDO();
                    fooddrugApplyImagesDO.setCreateName(getUserName());
                    fooddrugApplyImagesDO.setUpdateName(getUserName());
                    fooddrugApplyImagesDO.setApplyId(applyId);
                    fooddrugApplyImagesDO.setStatus(1);
                    fooddrugApplyImagesDO.setImg(url);
                    fooddrugApplyImagesDO.setType(type);
                    fooddrugApplyImagesService.save(fooddrugApplyImagesDO);
            }
        }
    }
    
    /**
     * 查询附件
     *
     * @param projectDO 项目
     * @param isUpdate  是否更新项目（更新就先删除以前图片，再新增）
     */
    private List<String>  queryAttach(Integer applyId,Integer type) {
    	List<String> list=new  ArrayList<String>();
		try {
			FooddrugApplyImagesQuery query=new FooddrugApplyImagesQuery();
			query.setApplyId(applyId);
			query.setType(type);
			List<FooddrugApplyImagesDO> imagesList=  fooddrugApplyImagesService.queryList(query);
			for (FooddrugApplyImagesDO fooddrugApplyImagesDO : imagesList) {
				list.add(fooddrugApplyImagesDO.getImg());
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return list;
    }

    
}
